package com.agadmin.manage;

import com.agadmin.config.CustomPasswordEncoder;
import com.agadmin.entity.user.Users;
import com.agadmin.mapper.UserMapper;
import com.agadmin.request.user.UserUpdateRequest;
import com.agadmin.response.user.UserUpdateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class UserUpdateManage {

    @Resource
    UserMapper userMapper;

    @Resource
    CustomPasswordEncoder encoder;

    public UserUpdateResponse updateUser(UserUpdateRequest req) {

        UserUpdateResponse res = new UserUpdateResponse();

        Users users = queryUser(req.getUserId());
        if (users == null) {
            res.setCode(402);
            res.setError("not found user");
            return res;
        }

        boolean matches = encoder.matches(req.getOldPwd(), users.getPassword());
        if (!matches) {
            res.setCode(403);
            res.setError("old password incorrect");
            return res;
        }

        if (!Objects.equals(req.getNewPwd(), req.getConfirmPwd())) {
            res.setCode(404);
            res.setError("new password and confirm password not equals");
            return res;
        }

        String newPwd = encoder.encode(req.getNewPwd());

        boolean update = update(newPwd, users.getId());
        if (!update) {
            res.setCode(406);
            res.setError("update fail");
        } else {
            res.setCode(200);
            res.setMsg("update successful");
        }

        return res;

    }


    private Users queryUser(String userId) {
        Users users = userMapper.selectById(userId);
        return users;
    }

    private boolean update(String pwd, String id) {

        Users users = new Users();
        users.setId(null);
        users.setCreateTime(null);
        users.setPassword(pwd);

        LambdaQueryWrapper<Users> qw = new LambdaQueryWrapper();
        qw.eq(Users::getId, id);

        int update = userMapper.update(users, qw);

        return update > 0;
    }


}
